package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author wzm
 * @create 2023-07-17 9:14
 * project_name:javaweb2306
 * file:LoginFilter
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断哪些资源直接访问  哪些资源不可以
        //1.将可以直接放行的资源定义出来
        String[] urls = {"/imgs/","/js/","/css/","/login.html","/login.jsp","/loginServlet","/register.html","/register.jsp","/registerServlet","/codeServlet"};

        //2.检测到访问路径和放行的资源匹配直接放行
        //获取请求路径
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getRequestURL().toString();//xxxx/index.jsp

        //请求路径和放行资源对比
        for(String s : urls){
            //用数组元素与路径对比
            if(url.contains(s)){
                //路径匹配到了需要放行
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }

        }


        //3.如果已经登录了可以访问内部资源 index
        //取出登录以后存储的值session
        Object loginUser = request.getSession().getAttribute("loginUser");
        if(loginUser == null){//如果登录用户为null 未登录
            //跳转到登录页（前后端不分离）
            //重定向  转发 => login.jsp

            //告诉浏览器（响应数据未登录） 适合前后端分离
            servletResponse.getWriter().write("nologin");

        }else{//登录了
            //放行
            filterChain.doFilter(servletRequest,servletResponse);

        }


    }
}
